package com.dd.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.dd.common.enums.ErrorEnum;
import com.dd.common.utils.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 统一捕获异常并返回标准格式 R<?>
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // ================== 业务异常 ==================

    /**
     * 业务异常（可预期，如参数校验、业务规则拒绝）
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public AjaxResult<?> handleBusinessException(BusinessException e) {
        log.warn("业务异常 [code={}]: {}", e.getCode(), e.getMessage());
        return AjaxResult.fail(e.getCode(), e.getMessage());
    }

    // ================== sa-token 登录与权限校验 ==================
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public AjaxResult<?> handleNotLoginException(NotLoginException e) {
        log.warn("用户未登录: {}", e.getMessage());
        return AjaxResult.fail(ErrorEnum.UNAUTHORIZED);
    }

    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public AjaxResult<?> handleNotPermissionException(NotPermissionException e) {
        log.warn("用户无权限: {}", e.getPermission());
        return AjaxResult.fail(ErrorEnum.FORBIDDEN);
    }

    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public AjaxResult<?> handleNotRoleException(NotRoleException e) {
        log.warn("用户无角色: {}", e.getRole());
        return AjaxResult.fail(ErrorEnum.FORBIDDEN);
    }

    // ================== 参数校验与绑定异常 ==================

    /**
     * 处理 @RequestParam、@PathVariable 参数类型转换异常（如 id=aaa）
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult<?> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException e) {
        log.warn("请求参数类型错误: {}", e.getName());
        return AjaxResult.fail(ErrorEnum.PARAMS_TYPE_ERROR.getCode(), ErrorEnum.PARAMS_TYPE_ERROR.getMsg() + ": " + e.getName());
    }

    /**
     * 请求体 @RequestBody json或xml参数校验失败（@Valid + DTO）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String messages = e.getBindingResult().getFieldErrors().stream()
                .map(item -> item.getField() + ": " + item.getDefaultMessage())
                .collect(Collectors.joining(", "));
        log.warn("请求体参数校验失败: {}", messages);
        return AjaxResult.fail(ErrorEnum.PARAMS_VALID_ERROR, messages);
    }

    /**
     * 表单数据参数绑定异常（@ModelAttribute + @Valid），也就是以对象接收 queryString 或 form-data  (application/x-www-form-urlencoded)
     * 对象参数中使用各种验证注解，验证失败也是抛出 BindException 异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult<?> handleBindException(BindException e) {
        String messages = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        log.warn("对象参数绑定异常: {}", messages);
        return AjaxResult.fail(ErrorEnum.BAD_REQUEST.getCode(), messages);
    }


    /**
     * JSR-303 注解参数校验失败（如 @NotBlank 等验证注解在方法参数上，getName(@NotBlank String name)）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult<?> handleConstraintViolationException(ConstraintViolationException e) {
        String messages = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        log.warn("方法上参数校验失败: {}", messages);
        return AjaxResult.fail(ErrorEnum.PARAMS_VALID_ERROR.getCode(), messages);
    }

    /**
     * 缺少必要请求参数（如 (@RequestParam String name)，注：不显式写出 @RequestParam 默认是可选的）
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        String msg = String.format("缺少必要参数: %s (%s)", e.getParameterName(), e.getParameterType());
        log.warn(msg);
        return AjaxResult.fail(ErrorEnum.PARAMS_MISSING.getCode(), msg);
    }

    /**
     * 请求体无法解析（如 JSON 格式错误）
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("请求体解析失败: {}", e.getMessage());
        return AjaxResult.fail(ErrorEnum.PARAMS_FORMAT_ERROR.getCode(), ErrorEnum.PARAMS_FORMAT_ERROR.getMsg());
    }

    /**
     * 不支持的 Content-Type（如 @RequestBody 接口要求 json, 但传表单类型 application/x-www-form-urlencoded）
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public AjaxResult<?> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
        String msg = "不支持的 Content-Type: " + ex.getContentType();
        log.warn(msg);
        return AjaxResult.fail(ErrorEnum.UNSUPPORTED_CONTENT_TYPE.getCode(), msg);
    }


    // ================== HTTP 相关异常 ==================

    /**
     * 请求方法不支持（如 GET /user/all 接口，用 POST 调用）
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public AjaxResult<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        String msg = String.format("不支持的请求方式: %s", e.getMethod());
        log.warn(msg);
        return AjaxResult.fail(ErrorEnum.REQUEST_METHOD_ERROR.getCode(), msg);
    }

    /**
     * 接口不存在（需配合配置 spring.mvc.throw-exception-if-no-handler-found=true 后生效，否则 SpringMVC 会默认处理）
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public AjaxResult<?> handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.warn("接口不存在: {} {}", e.getHttpMethod(), e.getRequestURL());
        return AjaxResult.fail(ErrorEnum.NOT_FOUND.getCode(), "请求的接口不存在");
    }

    // ================== 数据层异常（可选）==================

    /**
     * MyBatis-Plus 框架异常（如条件构造错误）
     */
    @ExceptionHandler(org.apache.ibatis.exceptions.PersistenceException.class)
    public AjaxResult<?> handleMyBatisPersistenceException(org.apache.ibatis.exceptions.PersistenceException e) {
        log.error("MyBatis 持久层异常", e);
        return AjaxResult.fail(ErrorEnum.SYSTEM_ERROR.getCode(), "数据库访问异常");
    }

    /**
     * MyBatis-Plus 特有异常（如插件配置错误）
     */
    @ExceptionHandler(com.baomidou.mybatisplus.core.exceptions.MybatisPlusException.class)
    public AjaxResult<?> handleMybatisPlusException(com.baomidou.mybatisplus.core.exceptions.MybatisPlusException e) {
        log.error("MyBatis-Plus 异常", e);
        return AjaxResult.fail(ErrorEnum.SYSTEM_ERROR.getCode(), "数据库操作异常");
    }

    /**
     * 数据库访问异常（如 SQL 异常）
     */
    @ExceptionHandler(DataAccessException.class)
    public AjaxResult<?> handleDataAccessException(DataAccessException e) {
        log.error("数据库访问异常", e); // 始终记录 error 日志

        // 1. 唯一键冲突：如 username 重复
        if (e instanceof DuplicateKeyException) {
            log.warn("数据库唯一键冲突: {}", e.getMessage());
            return AjaxResult.fail(ErrorEnum.DATA_EXISTS.getCode(), "数据已存在，请检查是否重复提交");
        }

        // 2. 数据完整性违规，这个异常是个“大杂烩”，包括：如字段超长、非空、外键约束等
        if (e instanceof DataIntegrityViolationException) {
            DataIntegrityViolationException dive = (DataIntegrityViolationException) e;
            String msg = dive.getMessage();

            // 尝试提取更友好的提示
            if (msg != null) {
                if (msg.contains("length") || msg.contains("too long")) {
                    log.warn("字段长度超限");
                    return AjaxResult.fail(ErrorEnum.PARAMS_VALID_ERROR.getCode(), "提交的数据字段长度超限");
                } else if (msg.contains("null") || msg.contains("NOT NULL")) {
                    log.warn("字段不允许为空");
                    return AjaxResult.fail(ErrorEnum.PARAMS_MISSING.getCode(), "必填数据未填写");
                } else if (msg.contains("foreign key")) {
                    log.warn("外键约束失败");
                    return AjaxResult.fail(ErrorEnum.PARAMS_VALID_ERROR.getCode(), "关联数据不存在，请检查引用关系");
                }
            }

            // 默认提示
            log.warn("数据完整性违规: {}", msg);
            return AjaxResult.fail(ErrorEnum.PARAMS_VALID_ERROR.getCode(), "数据不符合规则，请检查输入内容");
        }

        // 3. 其他数据库异常（连接失败、驱动错误、SQL 解析错误等）→ 系统错误
        log.error("未分类的数据库异常", e);
        return AjaxResult.fail(ErrorEnum.SYSTEM_ERROR.getCode(), "数据库操作失败，请稍后重试");
    }

    // ================== 系统未知异常（兜底）==================

    /**
     * 兜底异常处理：捕获所有未处理的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult<?> handleUnexpectedException(Exception e) {
        log.error("系统未预期异常", e);
        return AjaxResult.fail(ErrorEnum.SYSTEM_ERROR.getCode(), ErrorEnum.SYSTEM_ERROR.getMsg());
    }
}
